<template>
	<el-dialog
		v-model="dialogVisible"
		class="alert-dialog"
		width="480"
		align-center
		@close="cancelClick"
		:close-on-click-modal="false"
		draggable
	>
		<template #header>
			<div class="alert-dialog-title">
				<el-icon><WarningFilled /></el-icon>
				{{ options.title }}
			</div>
		</template>
		<div class="alert-dialog-content">
			<p v-html="options.content"></p>
			<div class="alert-dialog-date" v-if="options.showDate">
				<label>日期选择</label>
				<el-date-picker
					v-model="timer2"
					type="daterange"
					format="YYYY-MM-DD"
					value-format="YYYY-MM-DD"
					:shortcuts="shortcuts"
					:clearable="false"
					:disabled-date="disabledData"
					range-separator="至"
					start-placeholder="开始时间"
					end-placeholder="结束时间"
					@change="validateTime"
				/>
			</div>
			<div v-if="options.showDate && showErrorTime" class="sxzMust">选择范围超过7天，请重新选择</div>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button v-show="options.showCancelButton" @click="cancelClick"> {{ options.cancelButtonText }} </el-button>
				<el-button v-show="options.showConfirmButton" type="primary" @click="confirmClick">
					{{ options.confirmButtonText }}
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
import { shortcuts, getTime } from "@/utils/time";

const props = defineProps({
	//是否显示弹出框
	modelValue: {
		type: Boolean,
		default: false
	},
	//配置选项
	options: {
		type: Object,
		default: () => {
			return {
				title: "", //标题
				content: "", //内容
				showCancelButton: false, //是否显示取消按钮
				showConfirmButton: false, //是否确定按钮
				cancelButtonText: "取消", //取消按钮的文本内容
				confirmButtonText: "确定", //确定按钮的文本内容
				showDate: false //是否显示日期选择
			};
		}
	}
});
const showErrorTime = ref(false);
const timer2 = ref([getTime(Date.now() - 6 * 24 * 60 * 60 * 1000), getTime(Date.now())]);
const emit = defineEmits(["confirm", "update:modelValue"]);
const dialogVisible = computed({
	get() {
		return props.modelValue;
	},
	set(value) {
		emit("update:modelValue", value);
	}
});
const disabledData = date => {
	return date.getTime() > Date.now() - 8.64e6;
};
const isGreaterThan7Days = (date1, date2) => {
	let timeDiff = Math.abs(date2.getTime() - date1.getTime());
	let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
	return diffDays > 6;
};
const cancelClick = () => {
	emit("update:modelValue", false);
};
const confirmClick = () => {
	if (showErrorTime.value) return;
	emit("update:modelValue", false);
	emit("confirm", props.options.showDate ? timer2 : "");
};
const validateTime = time => {
	if (isGreaterThan7Days(new Date(time[0]), new Date(time[1]))) {
		showErrorTime.value = true;
	} else {
		showErrorTime.value = false;
	}
};
</script>

<style scoped lang="scss">
.sxzMust {
	color: #f56c6c;
	font-size: 12px;
	text-align: left;
	position: relative;
	margin-left: 62px;
}
</style>
